package com.starblink.guangconfig.ui.part

import android.content.Context
import com.starblink.android.basic.bridge.BridgeCommand
import com.starblink.android.basic.bridge.BridgeUtil
import com.starblink.android.basic.ext.runOnUIThread
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.network.base.BaseApiClient
import com.starblink.android.charles.CharlesManager
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.basic.util.CheckUtil
import com.starblink.basic.util.CommUtils
import com.starblink.guangconfig.databinding.ActivityGuangUpConfigBinding
import com.starblink.guangconfig.ui.GuangUpConfigVM

//抓包平替
object CharlesPart {
    fun handleVM(context: Context, m: GuangUpConfigVM, vb: ActivityGuangUpConfigBinding) {
        var uploadCheckStatus = CharlesManager.isUploadPacketInfo()
        var mockCheckStatus = CharlesManager.isMockPacketInfo()
        vb.charlesGuide.charlesGuideOpen.isChecked = uploadCheckStatus
        vb.charlesGuide.charlesGuideOpen.setOnClickListener {
            uploadCheckStatus = !uploadCheckStatus
            vb.charlesGuide.charlesGuideOpen.isChecked = uploadCheckStatus
            CharlesManager.setUploadPacketInfo(uploadCheckStatus)
            BridgeUtil.sendCommonData(BridgeCommand.Common.clearUserAgentData, "",true) //状态同步给H5
            toast(if(uploadCheckStatus) "开启抓包" else "关闭抓包")
        }

        vb.charlesGuide.mockGuideOpen.isChecked=mockCheckStatus
        vb.charlesGuide.mockGuideOpen.setOnClickListener {
            if(!uploadCheckStatus){
                toast("请先开启抓包")
                return@setOnClickListener
            }
            mockCheckStatus = !mockCheckStatus
            vb.charlesGuide.mockGuideOpen.isChecked = mockCheckStatus
            CharlesManager.setMockPacketInfo(mockCheckStatus)
            BridgeUtil.sendCommonData(BridgeCommand.Common.clearUserAgentData, "",true)//状态同步给H5
            toast(if(mockCheckStatus) "开启Mock" else "关闭Mock")
            if(!mockCheckStatus){
                //关闭mock调下取消mock接口
                CharlesManager.reqCancelMock()
            }
        }

        vb.charlesGuide.btnCharles.setOnClickListener {
            var url: String = vb.webGuide.etWebGuide.text.toString()
            if (CheckUtil.isEmpty(url)) {
                toast("轻扫描二维码获取绑定路径")
                return@setOnClickListener
            }

            CharlesManager.reqBindCatch(url, success = {
                runOnUIThread {
                    toast("抓包绑定成功")
                }
            }, fail = {
                runOnUIThread {
                    toast("抓包绑定失败！！！")
                }
            })
        }
    }
}